#!/bin/bash

echo -e "UPDATE\t: $0 START `date`"

sudo apt-get update

REBOOT=0
OPTIND=1
while getopts "r" opt; do
    case "$opt" in
    r)  REBOOT=y
        ;;
    esac
done
shift $((OPTIND-1))
[ "$1" = "--" ] && shift

if [ "$1" == "test" ]; then
    echo -e "UPDATE\t: UPDATE TEST COMPLETED"
    exit 0;
fi

if [ "$REBOOT" == "0" ]; then
    while true; do
        echo -e "UPDATE\t: SC-Voice update requires a reboot"
        read -p "UPDATE  : Reboot after update? [y,n]:" REBOOT
        case $REBOOT in
            [y]* ) echo -e "UPDATE\t: (will reboot after update)"; break;;
            [n]* ) break;;
               * ) echo "        : Please enter 'y' or 'n'";;
        esac
    done
fi

echo -e "UPDATE\t: chown " `whoami`
sudo chown -R $(whoami):$(whoami) * .*

MSG=`type rg`
RC=$?; if [ "$RC" == "0" ]; then
    echo -e "UPDATE\t: $MSG (OK)"
else
    echo -e "UPDATE\t: installing ripgrep"
    curl -LO https://github.com/BurntSushi/ripgrep/releases/download/12.1.1/ripgrep_12.1.1_amd64.deb
    sudo dpkg -i ripgrep_12.1.1_amd64.deb
fi

MSG=`type rotatelogs`
RC=$?; if [ "$RC" == "0" ]; then
    echo -e "UPDATE\t: $MSG (OK)"
else
    echo -e "UPDATE\t: installing apache2-utils for rotatelogs (sudo)"
    sudo apt-get update -y
    sudo apt-get install -y apache2-utils
fi

echo -e "UPDATE\t: npm install..."
npm install
sync

echo -e "UPDATE\t: Building web server..."
if [ -e dist ]; then
    rm -rf dist
fi
npm run build
sync

echo -e "UPDATE\t: Upating offline content..."
mkdir -p local
if [ ! -e local/ebt-data ]; then
    echo -e "UPDATE\t: installing ebt-data..."
    pushd local
    git clone https://github.com/sc-voice/ebt-data
    popd
fi
echo -e "UPDATE\t: fetching latest ebt-data..."
pushd local/ebt-data
BRANCH=published
if git checkout $BRANCH >& /dev/null; then
  echo -e "UPDATE\t: on $BRANCH branch" 
else
  echo -e "UPDATE\t: fetching $BRANCH branch" 
  git track --track origin/$BRANCH $BRANCH
  git checkout $BRANCH
fi
echo -e "UPDATE\t: Refreshing $BRANCH fork from Github..." && \
git pull --rebase 
popd

echo -e "UPDATE\t: clearing memoization caches"
rm -rf local/memo

if [ "$REBOOT" == "y" ]; then
    sudo shutdown -r now
fi

echo -e "UPDATE\t: $0 END `date`"
